package com._21cn.fetch.utils;

import com._21cn.cms.article.entity.Article;
import com._21cn.cms.article.entity.ArticleThumbPicture;
import com._21cn.cms.article.utils.FormatContentUtil;
import com._21cn.framework.http.HttpCaller;
import com._21cn.framework.utils.DateUtil;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.util.*;

public class FetchBashi {

    private static String postUrl = "http://admin.cms.qiaoliba.com/admin/article/article/save.do";

    private static String listUrl = "https://new.hoteastday.com/api/cat_page_news/16/z00577/100/0";

    private static String getContent(){
        try {
            URL link = new URL(listUrl);
            InputStream is = link.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder strBuilder = new StringBuilder();
            String sLine = null;
            while ((sLine = br.readLine()) != null) {
                strBuilder.append(sLine);
                strBuilder.append("\r\n");
            }
            br.close();
            String content = strBuilder.toString();
            return content;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static List<Article> getList() {
        LinkedList<Article> list = new LinkedList<Article>();
        try {

            String content = getContent();
            JSONArray array = JSONObject.parseArray(content);
            for ( Object object: array){
                Article article = new Article();
                JSONObject json = (JSONObject) object;
                JSONArray jArray = json.getJSONArray("content_img_list");

                List<String> picUrlList = new ArrayList<String>();
                for (Object obj : jArray){
                    String pic = (String) obj;
                    picUrlList.add(pic);
                }
                if(!picUrlList.isEmpty()){
                    article.setThumbPicUrlListStr(StringUtil.list2Str(picUrlList));
                }

                String articleUrl = json.getString("url");
                String source = json.getString("source");
                String title = json.getString("title");
                article.setArticleUrl(articleUrl);
                article.setSourceName(source);
                article.setTitle(title);

                list.add(article);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<String> extractPictureListFromContent(List<String> pictureUrlList) {
        String fetUrl = "http://admin.cms.qiaoliba.com/pictureFetch.do?status=1";
        List<String> picUrlList = new ArrayList();
        try {
            JSONObject array;
            if (pictureUrlList!=null && pictureUrlList.size()>0) {
                String urls = "";
                int i = 0;
                for (String sourceUrl : pictureUrlList) {
                    urls = urls + ",21cn.com," + sourceUrl;
                    i++;
                    if(i>6){
                        break;
                    }
                }
                if (!StringUtil.isEmpty(urls)) {
                    urls = urls.substring(",21cn.com,".length(), urls.length());
                }
                String json = HttpCaller.post(fetUrl).addParam("url", urls).call().getString();
                System.out.println("json:" + json);
                array = JSONObject.parseObject(json);
                for (String sourceUrl : pictureUrlList) {
                    JSONObject obj = array.getJSONObject(sourceUrl);
                    String url = obj.getString("url");
                    picUrlList.add(url);
                }
            }
        }catch (Exception e){
            System.out.println("=========NO picture========");
        }

        return picUrlList;
    }

    public static void main(String[] args) {
        saveAuto();
//        saveLine();
    }

    public static void saveAuto(){
        List<Article> list = FetchBashi.getList();

        for (Article article : list){
            String content = article.getContent();
            String picUrlListStr = article.getThumbPicUrlListStr();
            List<String> thumbUrlList = StringUtil.str2List(picUrlListStr);
            List<String> urlList = extractPictureListFromContent(thumbUrlList);
            if(urlList.size()<3){
                continue;
            }
            String thumbUrl1 = urlList.get(0);
            String thumbUrl2 = urlList.get(1);
            String thumbUrl3 = urlList.get(2);

            HttpCaller.post(postUrl).addParam("title", StringUtil.utf82iso(article.getTitle()))
                    .addParam("content", StringUtil.utf82iso(content))
                    .addParam("sourceName", StringUtil.utf82iso(article.getSourceName()))
                    .addParam("mainColumnId", "24")
                    .addParam("articleUrl", article.getArticleUrl())
                    .addParam("publishStatus", "2")
                    .addParam("thumbPicUrl", thumbUrl1)
                    .addParam("thumbPicUrl", thumbUrl2)
                    .addParam("thumbPicUrl", thumbUrl3)
                    .addParam("topTimeStr", DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"))
                    .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .addHeader("Accept-Encoding", "gzip, deflate")
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Cookie", "admin_auth_key=xxt:value_admin")
                    .call();
        }
    }

}
